import 'package:sqflite/sqflite.dart';
import 'dbmanager.dart';

class User {
  int autoId;
  String name;
  String psd;
  String nickName;

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      columnName: name,
      columnPsd: psd,
      columnNickName: nickName,
    };
    if (autoId != null) {
      map[columnAutoId] = autoId;
    }
    return map;
  }

  User();

  User.fromMap(Map<String, dynamic> map) {
    autoId = map[columnAutoId];
    name = map[columnName];
    psd = map[columnPsd];
    nickName = map[columnNickName];
  }

  @override
  String toString() {
    return 'User{autoId: $autoId, name: $name, psd: $psd, nickName: $nickName}';
  }

}

final String tableUser = 'user';
final String columnAutoId = 'autoId';
final String columnName = 'name';
final String columnPsd = 'psd';
final String columnNickName = 'nickName';

class UserProvider {
  Database db;

  String _createTableSql = '''
  create table ${tableUser} (
    ${columnAutoId} integer primary key autoincrement,
    ${columnName} text not null,
    ${columnPsd} text not null,
    ${columnNickName} text not null )
  ''';

  Future createTable() async {
    DBManager.createTable(tableUser, _createTableSql);
  }

  insert(User user) async {
    user.autoId = await DBManager.getDb().insert(tableUser, user.toMap());
    return user;
  }

  findAll() async {
    List<Map> maps = await DBManager.getDb().query(tableUser);

    List<User> userList = List();
    for (int i = 0; i < maps.length; i++) {
      User u = User.fromMap(maps[i]);
      if (u != null) userList.add(u);
    }
    return userList;
  }

  getById(int id) async {
    List<Map> maps = await DBManager.getDb().query(tableUser,
        columns: [columnAutoId, columnName, columnPsd, columnNickName],
        where: '${columnAutoId} = ?',
        whereArgs: [id]);
    if (maps.length > 0) {
      return User.fromMap(maps.first);
    }
    return null;
  }

  delete(int id) async {
    return await DBManager.getDb()
        .delete(tableUser, where: '${columnAutoId} = ?', whereArgs: [id]);
  }
}
